package com.example.warehouse_manager.controller;


import com.example.warehouse_manager.entity.*;
import com.example.warehouse_manager.page.Page;
import com.example.warehouse_manager.service.InStoreService;
import com.example.warehouse_manager.service.PurchaseService;
import com.example.warehouse_manager.service.StoreService;
import com.example.warehouse_manager.utils.TokenUtils;
import com.example.warehouse_manager.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/purchase")
public class PurchaseController {

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private InStoreService inStoreService;

    @Autowired
    private TokenUtils tokenUtil;

    //添加采购单
    @RequestMapping("/purchase-add")
    public Result addPurchase(@RequestBody Purchase purchase){
        return purchaseService.savePurchase(purchase);
    }

    //查询所有仓库
    @RequestMapping("/store-list")
    public Result storeList(){
        List<Store> stores = storeService.queryAllStore();
        return Result.ok(stores);
    }

    //分页查询采购单
    @RequestMapping("/purchase-page-list")
    public Result purchaseListPage(Page page,Purchase purchase){
        page = purchaseService.queryPurchasePage(page, purchase);
        return Result.ok(page);
    }

    //删除采购单
    @RequestMapping("/purchase-delete/{buyId}")
    public Result deletePurchase(@PathVariable Integer buyId){
        return purchaseService.deletePurchaseById(buyId);
    }

    //根据id修改预计采购数量和实际采购数量
    @RequestMapping("/purchase-update")
    public Result updatePurchase(@RequestBody Purchase purchase){
        return purchaseService.updatePurchaseById(purchase);
    }

    //生成入库单的url接口
    @RequestMapping("/in-warehouse-record-add")
    public Result addInStore(@RequestBody Purchase purchase,
                             @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){

        //拿到当前登录用户的id
        CurrentUser currentUser = tokenUtil.getCurrentUser(token);
        int creatBy = currentUser.getUserId();

        //创建InStore对象封装入库单信息
        InStore inStore = new InStore();
        inStore.setCreateBy(creatBy);
        inStore.setStoreId(purchase.getStoreId());
        inStore.setProductId(purchase.getProductId());
        inStore.setInNum(purchase.getFactBuyNum());

        //执行业务
        Result result = inStoreService.saveInStore(inStore, purchase.getBuyId());

        return result;

    }

    //导出数据
    @RequestMapping("/exportTable")
    public Result exportTable(Page page, Purchase purchase){
        page = purchaseService.queryPurchasePage(page, purchase);
        List<?> resultList = page.getResultList();
        //响应
        return Result.ok(resultList);
    }

}
